﻿using Microsoft.AspNetCore.Mvc;
using RSFrame.Services;
using RSModels;
using RSModels.Data;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace RSWebAPIs.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class TasksController : ControllerBase
    {
        public TasksController(IAppointmentService appointmentService, IRSEventService rSEventService,
            ITaskDistributionService taskDistributionService)
        {
            AppointmentService = appointmentService;
            RSEventService = rSEventService;
            TaskDistributionService = taskDistributionService;
        }

        public IAppointmentService AppointmentService { get; set; }

        public IRSEventService RSEventService { get; set; }

        public ITaskDistributionService TaskDistributionService { get; set; }

        [HttpPost]
        public List<RSTask> GetCurrentTasks([FromForm] RSEvent rSEvent)
        {
            try
            {
                List<Appointment> temp = AppointmentService.GetUnprocessedAppointments();
                List<Appointment> qualifiedtemp = new();
                if (temp != null)
                {
                    foreach (var item in temp)
                    {
                        if (TaskDistributionService.IsInServiceRegion(rSEvent.Lng, rSEvent.Lat, item.Lng, item.Lat))
                            qualifiedtemp.Add(item);
                    }

                }
                return TaskDistributionService.GenerateTasks(qualifiedtemp);
            }
            catch
            {
                return null;
            }
        }

        [HttpPost("{sourceID},{stage},{driverID},{carID},{time},{content},{load}")]
        public ActionResult PostEvent(int sourceID, int stage, int driverID, int carID, string time, string content, float load)
        {
            ActionResult actionResult = new() { Status = "succeed" };
            try
            {
                Appointment source = AppointmentService.GetAppointment(sourceID);
                int? result = RSEventService.AddRSEvent(new RSEvent()
                {
                    Title = RSEventService.TitleStage[stage],
                    Content = content,
                    EventTime = time,
                    CarID = carID,
                    DriverID = driverID,
                    CurrentLoad = load,
                    Lng = source.Lng,
                    Lat = source.Lat
                });
                if (stage == 2)
                    AppointmentService.CompleteAppointment(source.ID);
                if (result == null)
                    actionResult.Status = "failed";
                else
                    actionResult.Details = result.ToString();
            }
            catch
            {
                actionResult.Status = "failed";
            }
            return actionResult;
        }

    }
}
